package com.example.loadbalancedemo;

import io.grpc.*;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author tanyong
 * @Version HellowordClient v1.0.0 2024/4/2 16:33 $$
 */
public class HelloWordClient {

    /**
     * 客户端对服务Greeter进行同步rpc调用 blockingStub
     */
    private final GreeterGrpc.GreeterBlockingStub blockingStub;


    public HelloWordClient(Channel channel) {
        // 创建一个新的阻塞式Stub，支持对服务的一元和流输出调用
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }

    public void greet(String name) {
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();

        HelloReply response;
        try {
            // 设置此次RPC调用的响应超时时间为1秒
            response = blockingStub.withDeadlineAfter(10, TimeUnit.SECONDS).sayHello(request);
            System.out.println(response.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 服务段连接地址
        List<InetSocketAddress> addressList = Arrays.asList(new InetSocketAddress("127.0.0.1", 60052),
                new InetSocketAddress("127.0.0.1", 60053));

        // 注册 NameResolverProvider
        NameResolverRegistry.getDefaultRegistry().register(new LoadBalanceNameResolverProvider(addressList));
        // 符合namesolver的有效URI
        String target = String.format("%s:///%s", HelloWordConstants.SCHEME, HelloWordConstants.SERVICE_NAME);


        // 创建channel
        ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
                .defaultLoadBalancingPolicy("round_robin")
                // 使用明文连接到服务器。默认情况下，将使用安全连接机制，如TLS。
                // 应仅用于测试或API的使用或交换的数据不敏感的API。
                .usePlaintext()
                .disableRetry()
                .build();

        try {
            HelloWordClient client = new HelloWordClient(channel);
            long current = System.currentTimeMillis();
            for (int i = 0; i < 10; i++) {
                Thread.sleep(5000);
                client.greet("测试");
            }
            System.out.println(System.currentTimeMillis() - current);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭channel
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }

    }
}

